#include "RoboterRaupe.h"
#include "Uart.h"

void UartInit(void){

	UCSR3B|=(1<<RXCIE3|1<<RXEN3|1<<TXEN3);
	UCSR3C|=((1 << UCSZ31)|(1 << UCSZ30)); // Asynchron 8N1 ;
	UBRR3 = UBRR_VAL;
}

int Send(unsigned char c){
    while(!(UCSR3A & (1 << UDRE3)));  /* warte, bis UDR bereit */
    UDR3 = c;                     /* sende Zeichen */
    return 0;
}

void UartSenden (char *s){
    while (*s){   /* so lange *s != '\0' also ungleich dem "String-Endezeichen" */
        Send(*s);
        s++;
    }
	Send('\n');
}

uint8_t uart_getc(void){
	//int Timeout;
	//Timeout=TCNT2+10;
    while (!(UCSR3A & (1<<RXC3))){   // warten bis Zeichen verfuegbar
		/*if ( Timeout >= TCNT2 ) {
			UartTimedOut=true;
			return 0;
		}*/
	}
    return UDR3;                   // Zeichen aus UDR an Aufrufer zurueckgeben
}

ISR(USART3_RX_vect){
	uint8_t i;
	if (UDR3==255){
		Uart.TransmissionActive=true;
		Uart.MessageComplete=false;
		Uart.MessageValid=false;
		Uart.MessageLength=0;
		return;
	}
	if (UDR3==0){
		Uart.BytePuffer[Uart.MessageLength]=UDR3;
		Uart.TransmissionActive=false;
		Uart.MessageComplete=true;
		for (i=0; i<=Uart.MessageLength; i+=3){
			switch (Uart.BytePuffer[i]){

				case 252: 	Licht[Uart.BytePuffer[i+1]-1] = Uart.BytePuffer[i+2];
							break;
				case 253:	Servo[Uart.BytePuffer[i+1]-1] = Uart.BytePuffer[i+2];
							break;
				case 254:	Motor[Uart.BytePuffer[i+1]-1] = Uart.BytePuffer[i+2];
							break;
			}
		}
		if ((Uart.MessageLength-i)==1)
			Uart.MessageValid=true;
		return;
	}
	if (Uart.TransmissionActive){
		Uart.BytePuffer[Uart.MessageLength]=UDR3;
		Uart.MessageLength++;
	}
}
					
/*

ISR(USART3_RX_vect){
	Uart.TimedOut=false;
	LED_Toggle();
	if (UDR3 == 255){
		Uart.Busy=true;
		Uart.MessageComplete=false;
		//Uart.PufferSize=0;
		while(Uart.PufferSize<=31){
			Uart.BytePuffer[Uart.PufferSize]=uart_getc();
			if (Uart.BytePuffer[Uart.PufferSize] == 0){
				Uart.MessageComplete=true;
				return;
			}
			Uart.PufferSize++;
		}
		Uart.PufferOverflow=true; //Puffer Overflow!
	}	
}
*/
